<?php
/**
 * Save.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/12
 * Time: 15:46
 */
namespace app\api\open\supplier;

use app\api\open\Base;
use app\api\model\SupplierModel;
use think\Db;
use think\Validate;

class Save extends Base
{
    protected $id = null;
    protected $saveData = [];
    /**
     * Save constructor.
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        $this->prevent();

        parent::__construct($param);

        // 验证请求参数
        $validate = new Validate([
			"is_enable" => "require",
			"store_id" => "require",
			"name" => "require"
        ],[
			"is_enable.require" => "是否启用（0否，1是）必填",
			"store_id.require" => "商店id必填",
			"name.require" => "名称必填"
        ]);
        $check = $validate->check($this->params);
        if($check === false){
            // 验证失败 输出错误信息
            throw new \Exception($validate->getError(),1);
        }
        if(!empty($this->params['id']))
        {
            $this->id = $this->params['id'];
        }
		// 是否启用（0否，1是）
		$this->saveData['is_enable'] = (int)$this->params['is_enable'];
		// 商店id
		$this->saveData['store_id'] = (int)$this->params['store_id'];
		// 名称
		$this->saveData['name'] = (string)$this->params['name'];
    }
    
    /**
     * @param array $param
     * @return array
     * @throws \Exception
     */
    public function index($param=[])
    {
        Db::startTrans();
        try
        {
            // 保存信息
            $id = SupplierModel::getInstance()->save($this->id,$this->saveData);
            if(!$id)
            {
                throw new \Exception("保存失败",2);
            }
        }
        catch (\Exception $e)
        {
            // 出现错误进行回滚处理
            Db::rollback();
            // 统一错误抛出
            throw new \Exception("保存失败：".$e->getMessage(),$e->getCode());
        }

        Db::commit();
        return ['id'=>empty($this->id)?$id:$this->id];
    }
}